#include "registerdialog.h"
#include "global.h"
#include "httpmgr.h"
#include "ui_registerdialog.h"

RegisterDialog::RegisterDialog(QWidget *parent)
    : QDialog(parent), ui(new Ui::RegisterDialog) {
  ui->setupUi(this);

  ui->pwd_edit->setEnabled(QLineEdit::Password);
  ui->confirm_pwd_edit->setEnabled(QLineEdit::Password);

  // 设置状态
  ui->err_tip->setProperty("state", "normal");
  repolish(ui->err_tip);

  connect(HttpMgr::GetInstance().get(), &HttpMgr::sig_reg_mod_finish, this,
          &RegisterDialog::slot_reg_mod_finish);
}

RegisterDialog::~RegisterDialog() { delete ui; }

void RegisterDialog::on_get_code_btn_clicked() {
  auto email = ui->email_edit->text();
  // 验证邮箱正则表达式
  QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
  bool match = regex.match(email).hasMatch();
  if (match) {
    // 发送验证码
  } else {
    showTip(tr("Email Address Err!"), false);
  }
}

void RegisterDialog::slot_reg_mod_finish(ReqId req_id, QString res,
                                         ErrorCodes err) {
  if (err != ErrorCodes::SUCCESS) {
    showTip("NetWork Request Err", false);
    return;
  }
  // 解析 JSON 字符串,res需转化为QByteArray
  QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
  // json解析错误
  if (jsonDoc.isNull()) {
    showTip(tr("json解析错误"), false);
    return;
  }
  // json解析错误
  if (!jsonDoc.isObject()) {
    showTip(tr("json解析错误"), false);
    return;
  }
  // 调用对应的逻辑,根据id回调。
  //  QJsonObject jsonObj = jsonDoc.object();
  _handlers[req_id](jsonDoc.object());

  return;
}

void RegisterDialog::initHttpHandlers() {
  // 注册获取验证码回包的逻辑
  _handlers.insert(ReqId::ID_GET_VERIFY_CODE,
                   [this](const QJsonObject &jsonObj) {
                     int error = jsonObj["error"].toInt();
                     if (error != ErrorCodes::SUCCESS) {
                       showTip(tr("参数错误"), false);
                       return;
                     }
                     auto email = jsonObj["email"].toString();
                     showTip(tr("验证码已发送到邮箱，注意查收"), true);
                     qDebug() << "email is " << email;
                   });
}

void RegisterDialog::showTip(QString str, bool b_ok) {
  if (b_ok) {
    ui->err_tip->setProperty("state", "normal");
  } else {
    ui->err_tip->setProperty("state", "err");
  }
  ui->err_tip->setText(str);
  repolish(ui->err_tip);
}
